#!/bin/bash
# 增强版监控脚本 - 记录重启原因和冷启动时间

WATCH_DIR="/home/ubuntu/PhotoEnhanceAI-web/1-gateway/02-api-gateway"
LOG_FILE="/home/ubuntu/PhotoEnhanceAI-web/1-gateway/shared/logs/auto-reload.log"
ALERT_FILE="/home/ubuntu/restart-alert.log"

echo "[$(date)] 🔍 开始监控 $WATCH_DIR" >> "$LOG_FILE"

inotifywait -m -e modify,create,move --include ".*\.py$" "$WATCH_DIR" | while read -r directory events filename; do
    
    echo "[$(date)] 📝 检测到文件变化: $directory$filename" >> "$LOG_FILE"
    echo "[$(date)] 🔄 等待5秒后重启服务..." >> "$LOG_FILE"
    
    # 记录重启告警
    echo "============================================" >> "$ALERT_FILE"
    echo "[$(date)] ⚠️  API Gateway 即将重启" >> "$ALERT_FILE"
    echo "触发文件: $directory$filename" >> "$ALERT_FILE"
    echo "事件类型: $events" >> "$ALERT_FILE"
    
    # 记录重启前的进程运行时间
    OLD_PID=$(pgrep -f "gunicorn.*5000.*app:app" | head -1)
    if [ ! -z "$OLD_PID" ]; then
        OLD_UPTIME=$(ps -p "$OLD_PID" -o etime= | xargs)
        echo "重启前运行时间: $OLD_UPTIME" >> "$ALERT_FILE"
    fi
    
    # 5秒冷却期
    sleep 5
    
    # 记录重启开始时间
    RESTART_START=$(date +%s)
    
    # 重启服务
    sudo systemctl restart photoenhance-gateway
    
    if [ $? -eq 0 ]; then
        # 等待服务完全启动（检查健康状态）
        sleep 3
        HEALTH_CHECK_START=$(date +%s)
        
        while true; do
            HEALTH=$(curl -s http://127.0.0.1:5000/api/v1/health 2>/dev/null | grep -o "healthy" | head -1)
            if [ "$HEALTH" == "healthy" ]; then
                RESTART_END=$(date +%s)
                COLD_START_TIME=$((RESTART_END - RESTART_START))
                echo "✅ 服务重启成功" >> "$ALERT_FILE"
                echo "冷启动时间: ${COLD_START_TIME}秒" >> "$ALERT_FILE"
                echo "[$(date)] ✅ 服务重启成功，冷启动耗时: ${COLD_START_TIME}秒" >> "$LOG_FILE"
                break
            fi
            
            # 超时检查（60秒）
            NOW=$(date +%s)
            if [ $((NOW - HEALTH_CHECK_START)) -gt 60 ]; then
                echo "❌ 服务启动超时（>60秒）" >> "$ALERT_FILE"
                echo "[$(date)] ❌ 服务启动超时" >> "$LOG_FILE"
                break
            fi
            
            sleep 2
        done
    else
        echo "❌ 服务重启失败" >> "$ALERT_FILE"
        echo "[$(date)] ❌ 服务重启失败" >> "$LOG_FILE"
    fi
    
    echo "============================================" >> "$ALERT_FILE"
    echo "---" >> "$LOG_FILE"
done
